package com.njqy.ticket.filter;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njqy.ticket.dto.common.LoginUser;
import com.njqy.ticket.entity.common.UserEntity;
import com.njqy.ticket.service.common.IUserService;
import com.njqy.ticket.util.CommonUtil;
import com.njqy.ticket.util.JwtUtils;
import com.njqy.ticket.util.R;
import com.njqy.ticket.util.WebUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Security;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private IUserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if(StringUtils.isBlank(token)){
            filterChain.doFilter(request, response);
            return;
        }
        String username = "";
        //解析token
        try {
            Claims claims = JwtUtils.getClaimsFromToken(token);
            username = CommonUtil.toStr(claims.get("subject"));
        }catch (Exception e){
            R result = new R(HttpStatus.FORBIDDEN.value(), "token非法", null);
            String json = JSON.toJSONString(result);
            WebUtil.renderString(response, json);
            return;
//            throw new RuntimeException("token非法");
        }
        //获取信息
        LoginUser loginUser = userService.userToLoginUser(username);
        //存入context
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
    }

}
